<template>
  <div class="resume-library">
    <el-row :gutter="10" class="mb8">
      <el-col :span="6">
        <div class="view-switch">
          <el-radio-group v-model="currentView" @change="handleViewChange">
            <el-radio-button :label="'all'">全部简历</el-radio-button>
            <el-radio-button :label="'my'">我的简历</el-radio-button>
            <el-radio-button :label="'favorite'">收藏简历</el-radio-button>
          </el-radio-group>
        </div>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Filter" @click="openFilter">筛选</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="UploadFilled" @click="openUploadDialog">上传简历</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Refresh" @click="refreshList">刷新</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Plus" @click="addResume">新建简历</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Export" @click="exportData">导出</el-button>
      </el-col>
      <el-col :span="6" :offset="11.5">
        <el-input v-model="searchQuery" placeholder="搜索简历..." prefix-icon="Search" @keyup.enter="handleSearch" />
      </el-col>
    </el-row>

    <el-card class="filter-card" v-if="filterVisible">
      <el-form :model="filterForm" inline label-width="80px">
        <el-form-item label="姓名">
          <el-input v-model="filterForm.name" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="岗位">
          <el-select v-model="filterForm.position" placeholder="全部">
            <el-option label="全部" value="" />
            <el-option label="前端开发" value="frontend" />
            <el-option label="后端开发" value="backend" />
            <el-option label="UI设计" value="ui" />
            <el-option label="产品经理" value="product" />
            <el-option label="数据分析" value="data" />
          </el-select>
        </el-form-item>
        <el-form-item label="工作经验">
          <el-select v-model="filterForm.experience" placeholder="全部">
            <el-option label="全部" value="" />
            <el-option label="应届生" value="fresh" />
            <el-option label="1-3年" value="1-3" />
            <el-option label="3-5年" value="3-5" />
            <el-option label="5年以上" value="5+" />
          </el-select>
        </el-form-item>
        <el-form-item label="学历">
          <el-select v-model="filterForm.education" placeholder="全部">
            <el-option label="全部" value="" />
            <el-option label="大专" value="college" />
            <el-option label="本科" value="bachelor" />
            <el-option label="硕士" value="master" />
            <el-option label="博士" value="doctor" />
          </el-select>
        </el-form-item>
        <el-form-item label="技能标签">
          <el-select v-model="filterForm.skills" placeholder="全部" multiple>
            <el-option v-for="skill in skillOptions" :key="skill.value" :label="skill.label" :value="skill.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="匹配度">
          <el-slider v-model="filterForm.matchScore" :min="0" :max="100" show-input />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleFilter">查询</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-table :data="resumeList" style="width: 100%" border v-loading="loading">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column prop="id" label="简历ID" width="80" />
      <el-table-column prop="name" label="姓名" width="100" />
      <el-table-column prop="studentId" label="学员ID" width="80" />
      <el-table-column prop="position" label="目标岗位" width="120" />
      <el-table-column prop="experience" label="工作经验" width="100" />
      <el-table-column prop="education" label="学历" width="100" />
      <el-table-column prop="skills" label="技能标签" width="200">
        <template #default="scope">
          <el-tag v-for="skill in scope.row.skills" :key="skill" size="small" style="margin-right: 5px;">{{ skill }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="matchScore" label="匹配度" width="80">
        <template #default="scope">
          <el-rate v-model="scope.row.matchScore" disabled :max="100" show-score />
        </template>
      </el-table-column>
      <el-table-column prop="version" label="版本" width="80" />
      <el-table-column prop="uploadTime" label="上传时间" width="180" />
      <el-table-column prop="viewCount" label="查看次数" width="80" />
      <el-table-column label="操作" align="center" width="250" fixed="right">
        <template #default="scope">
          <el-button link type="primary" icon="Eye" @click="viewResume(scope.row)">查看</el-button>
          <el-button link type="success" icon="Download" @click="downloadResume(scope.row)">下载</el-button>
          <el-button link type="warning" :icon="scope.row.favorite ? 'StarFilled' : 'Star'" @click="toggleFavorite(scope.row)">
            {{ scope.row.favorite ? '已收藏' : '收藏' }}
          </el-button>
          <el-button link type="info" icon="Share" @click="shareResume(scope.row)">分享</el-button>
          <el-button link type="danger" icon="Delete" @click="deleteResume(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 上传简历对话框 -->
    <el-dialog title="上传简历" v-model="uploadDialog.open" width="600px" append-to-body>
      <el-form :model="uploadForm" ref="uploadFormRef" label-width="80px">
        <el-form-item label="学员" prop="studentId">
          <el-select v-model="uploadForm.studentId" placeholder="请选择学员">
            <el-option v-for="student in studentList" :key="student.id" :label="student.name" :value="student.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="简历文件" prop="file">
          <el-upload
            ref="uploadRef"
            :auto-upload="false"
            :on-change="handleFileChange"
            :file-list="fileList"
            accept=".pdf,.doc,.docx"
            action="#"
          >
            <el-button type="primary">选择文件</el-button>
          </el-upload>
          <div class="el-form-item__help">支持PDF、Word格式</div>
        </el-form-item>
        <el-form-item label="版本说明" prop="versionNote">
          <el-input v-model="uploadForm.versionNote" type="textarea" placeholder="请输入版本说明" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="uploadDialog.open = false">取 消</el-button>
          <el-button type="primary" @click="uploadResume">上 传</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 简历详情对话框 -->
    <el-dialog title="简历详情" v-model="detailDialog.open" width="800px" append-to-body>
      <el-tabs v-model="activeTab">
        <el-tab-pane label="基本信息">
          <el-descriptions title="简历信息" :column="2">
            <el-descriptions-item label="姓名">{{ currentResume.name }}</el-descriptions-item>
            <el-descriptions-item label="性别">{{ currentResume.gender }}</el-descriptions-item>
            <el-descriptions-item label="年龄">{{ currentResume.age }}</el-descriptions-item>
            <el-descriptions-item label="联系方式">{{ currentResume.contact }}</el-descriptions-item>
            <el-descriptions-item label="目标岗位">{{ currentResume.position }}</el-descriptions-item>
            <el-descriptions-item label="期望薪资">{{ currentResume.salary }}</el-descriptions-item>
            <el-descriptions-item label="工作经验">{{ currentResume.experience }}</el-descriptions-item>
            <el-descriptions-item label="学历">{{ currentResume.education }}</el-descriptions-item>
            <el-descriptions-item label="毕业院校">{{ currentResume.school }}</el-descriptions-item>
            <el-descriptions-item label="专业">{{ currentResume.major }}</el-descriptions-item>
            <el-descriptions-item label="所在城市">{{ currentResume.city }}</el-descriptions-item>
            <el-descriptions-item label="求职状态">{{ currentResume.status }}</el-descriptions-item>
          </el-descriptions>
        </el-tab-pane>
        <el-tab-pane label="工作经历">
          <el-timeline v-if="currentResume.workExperienceList && currentResume.workExperienceList.length">
            <el-timeline-item v-for="(item, index) in currentResume.workExperienceList" :key="index" :timestamp="item.startDate + ' - ' + item.endDate">
              <el-card>
                <el-card-header bordered="false">
                  <div class="card-header">
                    <span>{{ item.company }}</span>
                    <span class="card-header-extra">{{ item.position }}</span>
                  </div>
                </el-card-header>
                <el-card-body>
                  <p>{{ item.description }}</p>
                </el-card-body>
              </el-card>
            </el-timeline-item>
          </el-timeline>
          <div v-else class="no-data">暂无工作经历数据</div>
        </el-tab-pane>
        <el-tab-pane label="项目经历">
          <el-timeline v-if="currentResume.projectExperienceList && currentResume.projectExperienceList.length">
            <el-timeline-item v-for="(item, index) in currentResume.projectExperienceList" :key="index" :timestamp="item.startDate + ' - ' + item.endDate">
              <el-card>
                <el-card-header bordered="false">
                  <div class="card-header">
                    <span>{{ item.name }}</span>
                    <span class="card-header-extra">{{ item.role }}</span>
                  </div>
                </el-card-header>
                <el-card-body>
                  <p>{{ item.description }}</p>
                  <div class="skills">
                    <span>技术栈：</span>
                    <el-tag v-for="skill in item.skills" :key="skill" size="small" style="margin-right: 5px;">{{ skill }}</el-tag>
                  </div>
                </el-card-body>
              </el-card>
            </el-timeline-item>
          </el-timeline>
          <div v-else class="no-data">暂无项目经历数据</div>
        </el-tab-pane>
        <el-tab-pane label="技能专长">
          <div v-if="currentResume.skills && currentResume.skills.length">
            <el-tag v-for="skill in currentResume.skills" :key="skill" size="medium" style="margin-right: 10px; margin-bottom: 10px;">{{ skill }}</el-tag>
          </div>
          <div v-else class="no-data">暂无技能数据</div>
        </el-tab-pane>
        <el-tab-pane label="版本历史">
          <el-table :data="currentResume.versionHistory" style="width: 100%" border>
            <el-table-column prop="version" label="版本号" width="80" />
            <el-table-column prop="uploadTime" label="上传时间" width="180" />
            <el-table-column prop="uploadBy" label="上传人" width="100" />
            <el-table-column prop="versionNote" label="版本说明" width="200" />
            <el-table-column label="操作" align="center" width="150">
              <template #default="scope">
                <el-button link type="primary" icon="Eye" @click="viewVersion(scope.row)">查看</el-button>
                <el-button link type="success" icon="Download" @click="downloadVersion(scope.row)">下载</el-button>
                <el-button link type="warning" icon="Check" @click="restoreVersion(scope.row)" v-if="!scope.row.isCurrent">恢复</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailDialog.open = false">关 闭</el-button>
          <el-button type="primary" @click="shareResume(currentResume)">分 享</el-button>
          <el-button type="success" @click="downloadResume(currentResume)">下 载</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 分享简历对话框 -->
    <el-dialog title="分享简历" v-model="shareDialog.open" width="600px" append-to-body>
      <el-form :model="shareForm" ref="shareFormRef" label-width="80px">
        <el-form-item label="企业" prop="company">
          <el-select v-model="shareForm.company" placeholder="请选择企业">
            <el-option v-for="company in companyList" :key="company.id" :label="company.name" :value="company.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="联系人" prop="contactPerson">
          <el-input v-model="shareForm.contactPerson" placeholder="请输入联系人" />
        </el-form-item>
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="shareForm.contactPhone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="联系邮箱" prop="contactEmail">
          <el-input v-model="shareForm.contactEmail" placeholder="请输入联系邮箱" />
        </el-form-item>
        <el-form-item label="推荐岗位" prop="position">
          <el-input v-model="shareForm.position" placeholder="请输入推荐岗位" />
        </el-form-item>
        <el-form-item label="推荐说明" prop="description">
          <el-input v-model="shareForm.description" type="textarea" placeholder="请输入推荐说明" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="shareDialog.open = false">取 消</el-button>
          <el-button type="primary" @click="submitShare">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, getCurrentInstance } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { listResume, getResume, uploadResume, downloadResume, deleteResume, toggleFavorite, shareResume, listStudent, listCompany } from '@/api/resumeLibrary';

// 组件实例
const { proxy } = getCurrentInstance();

// 状态管理
const loading = ref(false);
const searchQuery = ref('');
const currentView = ref('all');
const filterVisible = ref(false);
const activeTab = ref('basic');

// 列表数据
const resumeList = ref([]);
const studentList = ref([]);
const companyList = ref([]);
const skillOptions = ref([
  { value: 'html', label: 'HTML' },
  { value: 'css', label: 'CSS' },
  { value: 'javascript', label: 'JavaScript' },
  { value: 'typescript', label: 'TypeScript' },
  { value: 'vue', label: 'Vue' },
  { value: 'react', label: 'React' },
  { value: 'angular', label: 'Angular' },
  { value: 'node', label: 'Node.js' },
  { value: 'java', label: 'Java' },
  { value: 'python', label: 'Python' },
  { value: 'mysql', label: 'MySQL' },
  { value: 'mongodb', label: 'MongoDB' },
  { value: 'git', label: 'Git' },
]);

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 筛选表单
const filterForm = reactive({
  name: '',
  position: '',
  experience: '',
  education: '',
  skills: [],
  matchScore: 0
});

// 上传表单
const uploadForm = reactive({
  studentId: '',
  file: null,
  versionNote: ''
});

// 分享表单
const shareForm = reactive({
  company: '',
  contactPerson: '',
  contactPhone: '',
  contactEmail: '',
  position: '',
  description: ''
});

// 当前简历
const currentResume = ref({});

// 对话框状态
const uploadDialog = reactive({ open: false });
const detailDialog = reactive({ open: false });
const shareDialog = reactive({ open: false });

// 文件列表
const fileList = ref([]);

// 获取简历列表
function getResumeList() {
  loading.value = true;
  const query = {
    ...filterForm,
    pageNum: pagination.currentPage,
    pageSize: pagination.pageSize,
    view: currentView.value,
    keyword: searchQuery.value
  };
  listResume(query)
    .then(response => {
      resumeList.value = response.rows;
      pagination.total = response.total;
      loading.value = false;
    })
    .catch(error => {
      ElMessage.error('获取简历列表失败');
      loading.value = false;
    });
}

// 处理视图切换
function handleViewChange() {
  getResumeList();
}

// 打开筛选面板
function openFilter() {
  filterVisible.value = !filterVisible.value;
}

// 处理筛选
function handleFilter() {
  pagination.currentPage = 1;
  getResumeList();
}

// 重置筛选
function resetFilter() {
  filterForm.name = '';
  filterForm.position = '';
  filterForm.experience = '';
  filterForm.education = '';
  filterForm.skills = [];
  filterForm.matchScore = 0;
  getResumeList();
}

// 搜索
function handleSearch() {
  pagination.currentPage = 1;
  getResumeList();
}

// 刷新列表
function refreshList() {
  getResumeList();
}

// 打开上传对话框
function openUploadDialog() {
  uploadDialog.open = true;
  uploadForm.studentId = '';
  uploadForm.file = null;
  uploadForm.versionNote = '';
  fileList.value = [];
  // 获取学员列表
  getStudentList();
}

// 获取学员列表
function getStudentList() {
  listStudent().then(response => {
    studentList.value = response;
  });
}

// 处理文件选择
function handleFileChange(file, fileList) {
  uploadForm.file = file.raw;
  this.fileList = fileList;
}

// 上传简历
function uploadResume() {
  if (!uploadForm.studentId) {
    ElMessage.warning('请选择学员');
    return;
  }
  if (!uploadForm.file) {
    ElMessage.warning('请选择简历文件');
    return;
  }

  const formData = new FormData();
  formData.append('studentId', uploadForm.studentId);
  formData.append('file', uploadForm.file);
  formData.append('versionNote', uploadForm.versionNote);

  loading.value = true;
  uploadResume(formData)
    .then(response => {
      ElMessage.success('上传成功');
      uploadDialog.open = false;
      getResumeList();
      loading.value = false;
    })
    .catch(error => {
      ElMessage.error('上传失败');
      loading.value = false;
    });
}

// 查看简历
function viewResume(row) {
  loading.value = true;
  getResume(row.id)
    .then(response => {
      currentResume.value = response;
      detailDialog.open = true;
      loading.value = false;
    })
    .catch(error => {
      ElMessage.error('获取简历详情失败');
      loading.value = false;
    });
}

// 下载简历
function downloadResume(row) {
  downloadResume(row.id)
    .then(response => {
      const blob = new Blob([response.data], { type: 'application/octet-stream' });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = row.name + '_简历_' + row.version + '.pdf';
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
      ElMessage.success('下载成功');
    })
    .catch(error => {
      ElMessage.error('下载失败');
    });
}

// 切换收藏状态
function toggleFavorite(row) {
  toggleFavorite(row.id)
    .then(response => {
      row.favorite = !row.favorite;
      ElMessage.success(row.favorite ? '收藏成功' : '取消收藏成功');
    })
    .catch(error => {
      ElMessage.error('操作失败');
    });
}

// 打开分享对话框
function shareResume(row) {
  currentResume.value = row;
  shareForm.company = '';
  shareForm.contactPerson = '';
  shareForm.contactPhone = '';
  shareForm.contactEmail = '';
  shareForm.position = row.position;
  shareForm.description = '';
  shareDialog.open = true;
  // 获取企业列表
  getCompanyList();
}

// 获取企业列表
function getCompanyList() {
  listCompany().then(response => {
    companyList.value = response;
  });
}

// 提交分享
function submitShare() {
  if (!shareForm.company) {
    ElMessage.warning('请选择企业');
    return;
  }
  if (!shareForm.contactPerson) {
    ElMessage.warning('请输入联系人');
    return;
  }
  if (!shareForm.contactPhone) {
    ElMessage.warning('请输入联系电话');
    return;
  }
  if (!shareForm.contactEmail) {
    ElMessage.warning('请输入联系邮箱');
    return;
  }

  const data = {
    resumeId: currentResume.value.id,
    ...shareForm
  };

  shareResume(data)
    .then(response => {
      ElMessage.success('分享成功');
      shareDialog.open = false;
    })
    .catch(error => {
      ElMessage.error('分享失败');
    });
}

// 删除简历
function deleteResume(id) {
  ElMessageBox.confirm('确定要删除该简历吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteResume(id)
      .then(response => {
        ElMessage.success('删除成功');
        getResumeList();
      })
      .catch(error => {
        ElMessage.error('删除失败');
      });
  }).catch(() => {
    // 取消操作
  });
}

// 分页大小变化
function handleSizeChange(size) {
  pagination.pageSize = size;
  getResumeList();
}

// 当前页码变化
function handleCurrentChange(current) {
  pagination.currentPage = current;
  getResumeList();
}

// 页面加载时执行
onMounted(() => {
  getResumeList();
});
</script>

<style scoped>
.resume-library {
  padding: 20px;
}

.filter-card {
  margin-bottom: 15px;
}

.pagination-container {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}

.view-switch {
  margin-bottom: 10px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header-extra {
  color: #606266;
  font-size: 14px;
}

.no-data {
  text-align: center;
  padding: 20px;
  color: #909399;
}

.skills {
  margin-top: 10px;
}
</style>